//
//  MyPromotion.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/5/22.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "MyPromotion.h"
#import "QrCodeView.h"
#import "myPromotionCell.h"
#import "otherPromotionCell.h"
#import "detialSectionHeadView.h"
#import "tuiGuangModel.h"
#import <UShareUI/UShareUI.h>
@interface MyPromotion () {
    QrCodeView *CodeView;
}
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, copy) NSMutableArray *tuiGuangList;
@end

@implementation MyPromotion


    - (void)viewDidLoad {
        self.view.backgroundColor = [UIColor whiteColor];
        self.title = @"我的推广";
        CodeView = [[QrCodeView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 500)];
        CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - StatusBarAndNavigationBarHeight - TabbarSafeBottomMargin);
        self.tableView = [[UITableView alloc]initWithFrame:frame];
        if (![self.Type isEqualToString:@"2"]) {
            self.tableView.tableHeaderView = CodeView;
        }
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            //        if (iPhoneX) {
            //            self.detialView.contentInset = UIEdgeInsetsMake(0, 0, 88, 0);
            //        }else {
            //            self.detialView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
            //        }
            //        self.detialView.scrollIndicatorInsets = self.detialView.contentInset;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        [self.view addSubview:self.tableView];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.page = 1;
        [self addRefreshHeader];
        [self addRefreshFooter];
        [self confingureTableView];
        [self tuiGuangListRequest];
        [self addRightBtn];
    }
- (void)addRightBtn {
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    shareBtn.frame = CGRectMake(0, 0, 54, 30);
    [shareBtn setImage:[UIImage imageNamed:@"fenXiang"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *Item = [[UIBarButtonItem alloc]initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItem = Item;
}
- (void)share {
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareErWeiMaToPlatformType:platformType];
    }];
}
// MARK: - 下拉刷新
- (void)addRefreshHeader {
    [super addRefreshHeader];
}
- (void)addRefreshFooter {
    [super addRefreshFooter];
}

- (void)loadNew
{
    self.page = 1;
    [self tuiGuangListRequest];
}

- (void)loadMore
{
    if (!self.tuiGuangList.count) {
        [self endFooterRefresh];
        return;
    }
    self.page = self.page + 1;
    [self tuiGuangListRequest];
}
- (void)confingureTableView {
    // [super confingureTableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([myPromotionCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([myPromotionCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([otherPromotionCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([otherPromotionCell class])];
}
- (void)handleResponseData:(NSDictionary *)responseObject
{
    NSMutableArray *modelArray =  [tuiGuangModel mj_objectArrayWithKeyValuesArray:responseObject[@"userList"]];
    if (self.page == 1) {
        [self.tuiGuangList removeAllObjects];
    }
    if (modelArray.count > 0) {
        [self.tuiGuangList addObjectsFromArray:(NSArray *)modelArray];
        if (modelArray.count < 10) {
             [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    [self.tableView reloadData];
}
#pragma mark --- uitableViewDelegate and dataSource
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.tuiGuangList.count;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        return 40;
    }
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 50;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        if ([self.Type isEqualToString:@"2"]) {
            otherPromotionCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([otherPromotionCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = [self.tuiGuangList objectAtIndex:indexPath.row];
            return cell;
        }
        myPromotionCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([myPromotionCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = [self.tuiGuangList objectAtIndex:indexPath.row];
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        if (![self.Type isEqualToString:@"2"]) {
            MyPromotion *otherPromotion = [MyPromotion new];
            tuiGuangModel *model = [self.tuiGuangList objectAtIndex:indexPath.row];
            otherPromotion.ID = model.id;
            otherPromotion.Type = @"2";
            [self.navigationController pushViewController:otherPromotion animated:YES];
        }
        
    }
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        detialSectionHeadView *view = [[detialSectionHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        UIView *grayV = [[UIView alloc]initWithFrame:CGRectMake(0, 39.5, kScreenWidth, 0.5)];
        grayV.backgroundColor = [UIColor grayColor];
        [view addSubview:grayV];
        if ([self.Type isEqualToString:@"2"]) {
             [view setTitle:@"别人的推广"];
        }else {
             [view setTitle:@"我的推广"];
        }
        return view;
    }
#pragma mark ---
- (void)tuiGuangListRequest {
    NSDictionary *dic;
    NSString *url;
    if ([self.Type isEqualToString:@"2"]) {
        url = [[apiManger shareApiManger] OthersTuiGuang];
        dic = @{
                @"pager.pageNumber":@(self.page),
                @"pager.pageSize":@10,
                @"tgOneLevelUserId":self.ID,
                @"token":USERTOKEN,
                };
    }else {
        url = [[apiManger shareApiManger] myTuiGuang];
        dic = @{
              @"pager.pageNumber":@(self.page),
              @"pager.pageSize":@10,
              @"token":USERTOKEN,
              };
    }
    
    __weak typeof(self) weakSelf = self;
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        [weakSelf endRefreshing];
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            [weakSelf handleResponseData:responseObject];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user removeObjectForKey:@"codeUrl"];
            [user setObject:responseObject[@"codeUrl"] forKey:@"codeUrl"];
            [user synchronize];
            [weakSelf creatErWeiMaView];
        }else {
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [weakSelf endRefreshing];
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
- (void)creatErWeiMaView { //生成二维码
    [CodeView logoQrCode:CodeView.backView];
}
- (NSMutableArray *)tuiGuangList {
    if (!_tuiGuangList) {
        _tuiGuangList = [NSMutableArray array];
    }
    return _tuiGuangList;
}

#pragma mark ---- 分享WEB链接
- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType
{
    UIImage *image = [UIImage imageNamed:@"mine_bankCard_ABC_icon"];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    UMShareWebpageObject *ob = [UMShareWebpageObject shareObjectWithTitle:@"金艺社" descr:@"金艺社是一款理财与艺术融合的app，既可以给您提供爱好欣赏、收藏、还可以用来理财。" thumImage:data];
    ob.webpageUrl = @"https://itunes.apple.com/cn/app/jiu-qi-gong-ying-lian-ban/id1076758306?mt=8";
    UMSocialMessageObject *mobject = [UMSocialMessageObject messageObjectWithMediaObject:ob];
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:mobject currentViewController:self completion:^(id data, NSError *error) {
        
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}
#pragma mark ---- 分享Image
- (void)shareErWeiMaToPlatformType:(UMSocialPlatformType)platformType {
    UMShareImageObject *ErWeiMaImg = [UMShareImageObject shareObjectWithTitle:@"金艺社" descr:@"金艺社是一款理财与艺术融合的app，既可以给您提供爱好欣赏、收藏、还可以用来理财。" thumImage:nil];
    //RCQrCodeV *erweima = [[CRCQrCodeV alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    UIImage *img = [self imageWithUIView:CodeView];
    NSData *data = UIImageJPEGRepresentation(img, 1);
    ErWeiMaImg.shareImage = data;
    //ErWeiMaImg.shareImage = image;
    UMSocialMessageObject *mobject = [UMSocialMessageObject messageObjectWithMediaObject:ErWeiMaImg];
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:mobject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}
- (UIImage*)imageWithUIView:(UIView*)view {
    UIGraphicsBeginImageContext(view.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tImage;
}
@end
